package com.example.ole.taskqueue.Q.base;

import android.os.SystemClock;

import com.example.ole.taskqueue.Print;

import java.util.ArrayList;

public class XTask extends XTaskAbs {

    public XTask(int eventType) {
        super(eventType);
    }

    @Override
    public void compileProgram(ArrayList<Instruction> instructions) {
        instructions.add(this::createMuxer);
        instructions.add(this::writeSampleData);

        markCurrentAsBeginningOfTerminateAddress();
        instructions.add(this::closeMuxer);
        instructions.add(this::releaseMuxer);

        super.compileProgram(instructions);
    }

    private int __started = 0;

    private void createMuxer(XTaskAbs program) {
        XTask thisProgram = (XTask) program;
        thisProgram.__started = 1;
        Print.d(1, 1, TAG, "stage: " + 1);
        SystemClock.sleep(1000);//Fake creating Muxer.
    }

    private int __index = 0;
    private int __size = 20;

    private void writeSampleData(XTaskAbs program) {
        XTask thisProgram = (XTask) program;

        if (thisProgram.__index < thisProgram.__size) {
            Print.d(1, 1, TAG, "stage: " + 2 + "." + thisProgram.__index);
            thisProgram.__index++;
            SystemClock.sleep(100); //Fake creating WriteSampleData().
            pcGoto(false, -1); // re-run current instruction.
        }
    }

    private void closeMuxer(XTaskAbs program) {
        XTask thisProgram = (XTask) program;
        if (thisProgram.__started == 1) {
            Print.d(1, 1, TAG, "stage: " + 3 + " Terminate " + 1);
            SystemClock.sleep(1000);//Fake close Muxer.
        }
    }

    private void releaseMuxer(XTaskAbs program) {
        XTask thisProgram = (XTask) program;
        if (thisProgram.__started == 1) {
            Print.d(1, 1, TAG, "stage: " + 3 + " Terminate " + 2);
            SystemClock.sleep(1000);//Fake release Muxer.
            thisProgram.__started = 0;
        }
    }
}
